package com.gullmall.search.service.impl;


import com.alibaba.fastjson.JSON;
import com.gullmall.common.to.es.SkuEsModel;
import com.gullmall.common.utils.R;
import com.gullmall.search.config.ElasticsearchConfig;
import com.gullmall.search.constant.EsConstant;
import com.gullmall.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.apache.juli.logging.Log;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@Service
@Transactional
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Resource(name = "elasticsearchClient")
    private RestHighLevelClient rs;

    //商品上架
    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest =new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest =new IndexRequest();
            //索引名
            indexRequest.index(EsConstant.ProductIndex.INDEX_PRODUCT.getValue());
            indexRequest.id(skuEsModel.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(skuEsModel), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulkResponse = rs.bulk(bulkRequest, RequestOptions.DEFAULT);
        //true表示有错误,某个文档插入失败
        boolean b = bulkResponse.hasFailures();
        if (b){
            bulkResponse.buildFailureMessage();
            log.error(bulkResponse.buildFailureMessage());
        }
        return !b;
    }
}
